<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket</title>
    <script type="text/javascript" src="/jquery-3.5.0.min.js"> </script>
</head>
<body>
<h3>基于web socket 点对点通讯</h3> 【当前用户ID】：<input id="userId" name="userId" type="text" value="10"><br><br>
【对方用户ID】：<input id="toUserId" name="toUserId" type="text" value="20"><br> <br> 【发送信息】： <input id="sendMsg"
                                                                                              name="sendMsg" type="text"
                                                                                              value="hello websocket"><br><br>
【接收信息】： <div id="receiveMsg" style="color: purple"></div><br><br>
<button id="openBtn">开启socket</button>
<br><br>
<button id="sendBtn">发送消息</button>
<br><br>
</body>

<script>
    var socket;
$(function () {
    $("#openBtn").click(function () {
            if (typeof (WebSocket) == "undefined") {
                console.log("您的浏览器不支持WebSocket");
            } else {
                console.log("您的浏览器支持WebSocket");
                //实现化WebSocket对象，指定要连接的服务器地址与端口 建立连接
                var userId = document.getElementById('userId').value;
                var socketUrl = "ws://localhost:22599/websocket/" + userId;
                console.log(socketUrl);
                if (socket != null) {
                    socket.close();
                    socket = null;
                }
                socket = new WebSocket(socketUrl);
                //打开事件
                socket.onopen = function () {
                    console.log("websocket已打开");
                    //socket.send("这是来自客户端的消息" + location.href + new Date());
                };
                // 获得消息事件
                socket.onmessage = function (msg) {
                    console.log(msg.data);
                    $("#receiveMsg").append("<span>"+"接收消息："+msg.data+"</span><br>");
                    //发现消息进入 开始处理前端触发逻辑
                };
                //关闭事件
                socket.onclose = function () {
                    console.log("websocket已关闭");
                };
                //发生了错误事件
                socket.onerror = function () {
                    console.log("websocket发生了错误");
                }
            }
        }
    );
    $("#sendBtn").click(function () {
            if (typeof (WebSocket) == "undefined") {
                console.log("您的浏览器不支持WebSocket");
            } else {
                // console.log("您的浏览器支持WebSocket");
                var toUserId = document.getElementById('toUserId').value;
                var sendMsg = document.getElementById('sendMsg').value;
                var o = {};
                o.toUserId = toUserId;
                o.sendMsg = sendMsg;
                var msg = JSON.stringify(o);
                console.log(msg);
                $("#receiveMsg").append("<span>"+"发送消息："+sendMsg+"</span><br>");
                socket.send(msg);
            }
        }
    );
}) </script>
</html>